import { MouseEvent, MouseEventHandler, useId } from 'react';

import { Button } from '@/shared/ui';
import cn from 'classnames';
import { NextRouter, useRouter } from 'next/router';

import { useNavItems } from '../lib';
import cs from './Nav.module.scss';

function clickLink(
  event: MouseEvent<HTMLAnchorElement, globalThis.MouseEvent>,
  href: string,
  router: NextRouter,
  closeSelf?: () => void,
) {
  event.stopPropagation();
  router.push(href);
  closeSelf && closeSelf();
}

interface Props {
  className?: string;
  isMobile?: boolean;
  onMouseDown?: MouseEventHandler<HTMLElement>;
  closeSelf?: () => void;
}

export const Nav = ({ className, onMouseDown, closeSelf, isMobile }: Props) => {
  const componentId = useId();
  const router = useRouter();
  const navItems = useNavItems();
  return (
    <nav className={cn(cs.nav, className, isMobile ? cs.navMobile : cs.navDesktop)} onMouseDown={onMouseDown}>
      <ol className={cs.ol}>
        {Object.keys(navItems).map((id) => (
          <li key={id + componentId}>
            <Button
              className={cs.navItem}
              data-testid={`link-${id.split('/')?.[1]}`}
              href={id}
              link
              onClick={(event) => clickLink(event, id, router, closeSelf)}
            >
              {navItems[id as keyof typeof navItems]}
            </Button>
          </li>
        ))}
      </ol>
    </nav>
  );
};
